package org.csu.laboratoryequipment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.laboratoryequipment.common.CommonResponse;
import org.csu.laboratoryequipment.entity.History;
import org.csu.laboratoryequipment.entity.Searchrecord;
import org.csu.laboratoryequipment.persistence.HistoryMapper;
import org.csu.laboratoryequipment.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("HistoryService")
public class HistoryServiceImpl implements HistoryService {
    @Autowired
    private HistoryMapper historyMapper;

    public CommonResponse<List<History>> getHistorySearchByUid(String userid){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid",userid);
        // 按照时间倒序排列
        queryWrapper.orderByDesc("time");
        List<History> historyList = historyMapper.selectList(queryWrapper);
        System.out.println(historyList);
        //对于已经出现过的history_word结果进行移除
        Set<String> uniqueWords = new HashSet<>();
        // 遍历 historyList，移除重复的 history_word
        Iterator<History> iterator = historyList.iterator();
        while (iterator.hasNext()) {
            History history = iterator.next();
            String historyWord = history.getHistoryWord();

            // 如果 history_word 已经出现过，从列表中移除当前记录
            if (uniqueWords.contains(historyWord)) {
                iterator.remove();
            } else {
                // 否则，将 history_word 添加到已经出现过的集合中
                uniqueWords.add(historyWord);
            }
        }
        return CommonResponse.createForSuccess(historyList);
    }

    public CommonResponse<String> saveScore(String userid, String history_word, double score, double com_avg, Date time){

        History history = new History();
        history.setScore(score);
        history.setUserId(userid);
        history.setComAvg(com_avg);
        history.setHistoryWord(history_word);
        history.setTime(time);
        historyMapper.insert(history);
        return CommonResponse.createForSuccess("插入成功");
    }

    public CommonResponse<List<History>> getHistory(){

        List<History>historyList = historyMapper.selectList(null);
        return CommonResponse.createForSuccess(historyList);
    }

    public CommonResponse<List<History>> getHistoryByTime(Date startTime, Date endTime){
        // 创建查询条件
        QueryWrapper<History> queryWrapper = new QueryWrapper<>();
        // 使用 between 方法指定搜索时间范围
        queryWrapper.between("time", startTime, endTime);
        // 查询符合条件的数据
        List<History>historyList = historyMapper.selectList(queryWrapper);
        return CommonResponse.createForSuccess(historyList);
    }


}
